#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工程头文件路径配置加载工具
处理全局头文件路径的定制配置
"""

import os
import logging
from pathlib import Path

def generate(env):
    """
    生成工程头文件路径配置加载工具
    
    Args:
        env: SCons环境
    """
    _load_project_include_config(env)
    
    # 添加获取全局头文件路径的方法
    env.AddMethod(get_global_include_paths, 'GetGlobalIncludePaths')

def exists(env):
    """
    检查工具是否存在
    
    Args:
        env: SCons环境
        
    Returns:
        True
    """
    return True

def _load_project_include_config(env):
    """
    加载工程头文件路径配置
    
    Args:
        env: SCons环境
    """
    # 检查是否设置了PROJECT_INC_CONFIG环境变量
    project_inc_config = os.environ.get('PROJECT_INC_CONFIG')
    if not project_inc_config:
        return
    
    if not os.path.exists(project_inc_config):
        logging.warning(f"Project include config file not found: {project_inc_config}")
        return
    
    logging.info(f"Loading project include config from: {project_inc_config}")
    
    # 获取工程根目录
    project_root = env.get('PROJECT_ROOT', os.getcwd())
    
    # 存储全局头文件路径
    global_include_paths = []
    
    try:
        with open(project_inc_config, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                line = line.strip()
                
                # 跳过空行和注释行
                if not line or line.startswith('#'):
                    continue
                
                # 处理相对路径
                if os.path.isabs(line):
                    include_path = line
                else:
                    include_path = os.path.join(project_root, line)
                
                # 检查路径是否存在
                if os.path.exists(include_path):
                    global_include_paths.append(include_path)
                    logging.info(f"  Added global include path: {include_path}")
                else:
                    logging.warning(f"Include path does not exist (line {line_num}): {include_path}")
    
    except Exception as e:
        logging.error(f"Failed to load project include config: {e}")
        raise
    
    # 将全局头文件路径添加到SCons环境中
    if global_include_paths:
        # 添加到CPPPATH中，这样所有编译都会包含这些路径
        current_cpppath = env.get('CPPPATH', [])
        if isinstance(current_cpppath, str):
            current_cpppath = [current_cpppath]
        
        # 将全局路径添加到现有路径前面，确保优先级
        env['CPPPATH'] = global_include_paths + list(current_cpppath)
        
        # 同时存储到自定义变量中，供其他模块使用
        env['GLOBAL_INCLUDE_PATHS'] = global_include_paths
        
        logging.info(f"Added {len(global_include_paths)} global include paths to build environment")

def get_global_include_paths(env):
    """
    获取全局头文件路径列表
    
    Args:
        env: SCons环境
        
    Returns:
        全局头文件路径列表
    """
    return env.get('GLOBAL_INCLUDE_PATHS', [])